<template>
  <div class="login_container">
    <div class="login_box">
      <!--头像区域-->
      <div class="avatar_box">
        <img src="../assets/head.jpg" alt="" />
      </div>

      <div>
        <el-tabs v-model="activeName" class="login_tabs">
          <!-- 账号密码登录 -->
          <el-tab-pane label="账号密码登录" name="first">
            <div class="tab_content">
              <!-- 登录表单区域 -->
              <el-form
                label-width="0px"
                class="login_form"
                :model="loginForm"
                :rules="loginFormRules"
                ref="loginFormRef"
              >
                <!-- 用户名 -->
                <el-form-item prop="phone">
                  <el-input
                    type="text"
                    prefix-icon="iconfont icon-user"
                    v-model="loginForm.phone"
                    maxlength="11"
                  ></el-input>
                </el-form-item>
                <!-- 密码 -->
                <el-form-item prop="password" style="display: flex">
                  <el-input
                    prefix-icon="iconfont icon-3702mima"
                    v-model="loginForm.password"
                    style="width: 360px; margin-right: 10px"
                    type="password"
                    show-password
                  >
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <el-checkbox
                    v-model="loginForm.remember"
                    label="true"
                    @change="changeRadio($event)"
                    >记住密码</el-checkbox
                  >
                </el-form-item>
                <!-- 按钮 -->
                <el-form-item class="btns">
                  <el-button type="primary" round @click="onLoginByPwd"
                    >登录</el-button
                  >
                  <el-button type="success" round @click="toRegister"
                    >注册</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <a style="float: right; cursor: pointer" @click="toForgetPwd"
                    >找回密码</a
                  >
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>

          <!-- 手机验证码登录 -->
          <el-tab-pane label="手机验证码登录 " name="second">
            <div class="tab_content">
              <!-- 登录表单区域 -->
              <el-form
                label-width="0px"
                class="login_form"
                :model="loginForm"
                :rules="loginFormRules"
                ref="loginFormRef"
              >
                <!-- 用户名 -->
                <el-form-item prop="phone">
                  <el-input
                    prefix-icon="iconfont icon-user"
                    v-model="loginForm.phone"
                    maxlength="11"
                  ></el-input>
                </el-form-item>
                <!-- 验证码 -->
                <el-form-item prop="code" style="display: flex">
                  <el-input
                    prefix-icon="iconfont icon-3702mima"
                    v-model="loginForm.code"
                    style="width: 165px; margin-right: 10px"
                  >
                  </el-input>
                  <el-button
                    type="info"
                    @click="onSendLoginCode"
                    :disabled="isDisabled"
                    >{{ buttonName }}</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-checkbox
                    v-model="loginForm.remember"
                    label="true"
                    @change="changeRadio($event)"
                    >记住密码</el-checkbox
                  >
                </el-form-item>
                <!-- 按钮 -->
                <el-form-item class="btns">
                  <el-button type="primary" round @click="onLogin"
                    >登录</el-button
                  >
                  <el-button type="success" round @click="toRegister"
                    >注册</el-button
                  >
                </el-form-item>

                <el-form-item>
                  <a style="float: right; cursor: pointer" @click="toForgetPwd"
                    >找回密码</a
                  >
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>


<script>
import { login, sendLoginCode, loginByCode } from "../api/login.js";
export default {
  data() {
    return {
      buttonName: "发送短信",
      isDisabled: false,
      time: 60,
      activeName: "first",
      //这个User是用来登录的表单，从loginForm拿值
      User: {
        userName: "", //账号
        roles: "", //用户身份
        userHeadName: "", //用户头部的姓名
        remember: "",
      },
      phone: "",
      //定义一个登录表单的数据绑定对象
      loginForm: {
        phone: "",
        code: "",
        password: "",
        remember: false,
      },

      loginFormRules: {
        phone: [
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 11, //这个地方最后要改成手机号码长度
            max: 11,
            message: "请填写11位的手机号码",
            trigger: "blur",
          },
        ],
        code: [
          {
            min: 6,
            max: 6,
            message: "请输入6位的验证码",
            trigger: "blur",
          },
        ],
        password: [
          { message: "请输入密码", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "请填写1-15位的密码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    //通过验证码登录
    onLogin() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        loginByCode(this.loginForm)
          .then((res) => {
            if (res.data.code === 0 && res.data.data.roles[0] == "TEACHER") {
              this.User.roles = res.data.data.roles[0];
              this.User.userName = this.loginForm.phone;
              this.User.userHeadName = res.data.data.nickname;
              this.User.remember = this.loginForm.remember;
              localStorage.setItem("userInfo", JSON.stringify(res.data.data));
              this.saveUserOnlocal(this.User);
              this.$router.push("/");
            } else if (
              res.data.code === 0 &&
              res.data.data.roles[0] == "ADMIN"
            ) {
              this.User.roles = res.data.data.roles[0];
              this.User.userName = this.loginForm.phone;
              this.User.userHeadName = res.data.data.nickname;
              this.User.remember = this.loginForm.remember;
              localStorage.setItem("userInfo", JSON.stringify(res.data.data));
              this.saveUserOnlocal(this.User);
              this.$router.push("/");
            } else {
              this.$message({
                message: "登录失败了，请检查您的账号验证码",
                type: "warning",
              });
            }
          })
          .catch(() => {
            this.$message.error("请求出错");
          });
      });
    },

    //通过账号密码登录
    onLoginByPwd() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }

        login(this.loginForm)
          .then((res) => {
            if (res.data.code === 0 && res.data.data.roles[0] === "TEACHER") {
              this.User.roles = res.data.data.roles[0];
              this.User.userName = this.loginForm.phone;
              this.User.userHeadName = res.data.data.nickname;
              this.User.remember = this.loginForm.remember;

              localStorage.setItem("userInfo", JSON.stringify(res.data.data));
              this.saveUserOnlocal(this.User);
              this.$router.push("/");
            } else if (
              res.data.code === 0 &&
              res.data.data.roles[0] == "ADMIN"
            ) {
              this.User.roles = res.data.data.roles[0];
              this.User.userName = this.loginForm.phone;
              this.User.userHeadName = res.data.data.nickname;
              this.User.remember = this.loginForm.remember;
              localStorage.setItem("userInfo", JSON.stringify(res.data.data));
              this.saveUserOnlocal(this.User);
              this.$router.push("/");
            } else {
              this.$message({
                message: "登录失败了，请检查您的账号密码",
                type: "warning",
              });
            }
          })
          .catch(() => {
            this.$message.error("请求出错");
          });
      });
    },

    //验证码登录中，获取验证码
    onSendLoginCode() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        //获得倒计时
        let me = this;
        me.isDisabled = true;
        let interval = window.setInterval(function () {
          me.buttonName = "（" + me.time + "秒）后重新发送";
          --me.time;
          if (me.time < 0) {
            me.buttonName = "重新发送";
            me.time = 10;
            me.isDisabled = false;
            window.clearInterval(interval);
          }
        }, 1000);
        //下面这些是短信发送
        sendLoginCode(this.loginForm.phone)
          .then((res) => {
            if (res.data.code === 0) {
            } else {
              this.$message({
                message: "警告哦，这是一条警告消息",
                type: "warning",
              });
            }
          })
          .catch(() => {
            this.$message.error("请求出错");
          });
      });
    },
    //跳转去注册界面
    toRegister() {
      this.$router.push("/register");
    },

    saveUserOnlocal(TUser) {
      localStorage.setItem("User", JSON.stringify(TUser));
    },

    toForgetPwd() {
      this.$router.push("/forgetpwd");
    },

    changeRadio(val) {
      return (this.loginForm.remember = val);
    },
  },
};
</script>

<style lang="less" scoped>
.login_container {
  background-color: grey;
  height: 100%;
}
.login_box {
  width: 450px;
  height: 400px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  .avatar_box {
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
  .btns {
    display: flex;
    justify-content: flex-end;
  }
  .tab_content {
    margin-top: 10px;
    display: flex;
    width: 100%;
    justify-content: center;
  }
  .login_form {
    width: 80%;
  }
}
</style>
<style>
.login_box .login_tabs .el-tabs__header {
  margin: 60px 114px 0px;
}
</style>